package com.paulshiyc.imserver.websocket;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.BinaryMessage;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.PongMessage;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;

import com.paulshiyc.imserver.bean.User;
import com.paulshiyc.imserver.controller.BaseController;
/**
 * 自定义websocket处理器
 * @author PaulShi
 *
 */
@Service
public class MyHandler extends AbstractWebSocketHandler {
	private static final Logger logger = LogManager.getLogger(MyHandler.class);
	
	/**
	 * 建立连接后对应 
	 */
	@Override
	public void afterConnectionEstablished(WebSocketSession session) throws Exception {
		String sessionId = (String) session.getAttributes().get("sessionId");
		User user = BaseController.sessionAndUser.get(sessionId);
		BaseController.onlinUser.put(user.getUsername(), session);
	}
	/**
	 * 收到消息后 
	 */
	@Override
	public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
		if (message instanceof TextMessage) {
			//TODO 
			//TODO 
			//TODO 
		} else if (message instanceof BinaryMessage) {
			handleBinaryMessage(session, (BinaryMessage) message);
		} else if (message instanceof PongMessage) {
			handlePongMessage(session, (PongMessage) message);
		} else {
			throw new IllegalStateException("Unexpected WebSocket message type: " + message);
		}
	}
	/**
	 * 发送错误时
	 */
	@Override
	public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
		String sessionId = (String) session.getAttributes().get("sessionId");
		User user = BaseController.sessionAndUser.get(sessionId);
		BaseController.onlinUser.remove(user.getUsername(), session);
		super.handleTransportError(session, exception);
	}
	/**
	 * 关闭连接时
	 */
	@Override
	public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
		String sessionId = (String) session.getAttributes().get("sessionId");
		User user = BaseController.sessionAndUser.get(sessionId);
		BaseController.onlinUser.remove(user.getUsername(), session);
		super.afterConnectionClosed(session, status);
	}

}
